package vlms.controller;

import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import vlms.bean.*;





import vlms.service.VLMSServiceProxy;

/**
 * Servlet implementation class SignUp
 */
public class SignUp extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	private static Set<String> abbreviations = new HashSet<String>( 
	           ( Arrays.asList( new String[] {
			"AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", 
	               "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", 
			"MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", 
	               "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"
			} ) ) );
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SignUp() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		HttpSession session = request.getSession(true); 
		int personid=0;
		String destination = null;
		
				
		String firstName = request.getParameter("firstname");
		String lastName = request.getParameter("lastname");
		String emailId = request.getParameter("email");
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		String address = request.getParameter("address");
		String city = request.getParameter("city");
		String state = request.getParameter("state"); 
		String zipCode = request.getParameter("zipcode");
		String memberType = request.getParameter("Membertype");
		
		String creditCardType = request.getParameter("creditcard_type"); 
		String creditCardNum= request.getParameter("creditcardno");
		String creditCardCVV = request.getParameter("Cvvnumber");
		
		
		
		
		try {
		
		
			if(firstName == null || firstName.equals("")) {
				throw new Exception("First Name cannot be empty");
			}
			
			if(lastName == null || lastName.equals("")) {
				throw new Exception("Last Name cannot be empty");
			}
			
			if(emailId == null || emailId.equals("") || !isValidEmailAddress(emailId)) {
				throw new Exception("Invalid Email Addess Format");
			}
			
			if(userName == null || userName.length() < 8 || userName.length() > 45) {
				throw new Exception("Invalid Username Format");
			}
			if(password == null || !password.matches("((?=.*[0-9])(?=.*[A-Z])(?=.*[@#$%]).{8,45})")) {
				throw new Exception("Invalid Password Format");
			}
			
			
			if(address == null || address.equals("")) {
				throw new Exception("Address cannot be empty");
			}
			
			if(city == null || city.equals("")) {
				throw new Exception("City cannot be empty");
			}
			
			if(state == null || state.equals("")) {
				throw new Exception("Invalid State");
			}
			else if (!abbreviations.contains(state.toUpperCase())){
				throw new Exception("Invalid State");
			}
			
			if(zipCode == null || zipCode.equals("")) {
				throw new Exception("Zipcode cannot be empty");
			}
			else if(!isValidZipCode(zipCode)) {
				throw new Exception("Invalid ZipCode Format");
			}
			
			if(memberType == null || memberType.equals("") || !memberType.equals("PC") && !memberType.equals("SC") ) {
				throw new Exception("Invalid Member Type");			
			}
			
			
			
			if(creditCardType == null || creditCardType.equals("")) {
				throw new Exception("Please Select Credit Card Type");
			}
			
			
			if(creditCardNum == null || creditCardNum.equals("")){
				throw new Exception("Please Enter Credit Card Number");
			}
			else {
				try {
					Double.parseDouble(creditCardNum);
					if(creditCardNum.length() > 16) {
						throw new Exception("Credit Card Number cannot be greater than 16 digits");					
					}
					else if(creditCardNum.length() < 16){					
						throw new Exception("Credit Card Number cannot be less than 16 digits");					
					}
				}
				catch(NumberFormatException e) {
					throw new Exception("Invalid Credit Card Number");
				}
			}
			
			
			String cvv = creditCardCVV;
			if(cvv.equals("")) {
				throw new Exception("Please Enter CVV code");
			}
			
			try {
				Integer.parseInt(cvv);
			}
			catch(NumberFormatException e) {
				throw new Exception("Invalid CVV code");
			}
			if(cvv.length() > 3) {
				throw new Exception("cvv code cannot be greater than 3 digits");					
			}
			else if(cvv.length() < 3){					
				throw new Exception("cvv code cannot be less than 3 digits");					
			}
			
			
			
			
			 
			//System.out.println(fname + lname + username + password + email + address + city + state + zipcode + memberType +creditnumber + cardtype + cvvnumber);
			 Account account=new Account();
			 account.setUsername(userName);
			 account.setPassword(password);
			 
			
			 
			 Person person=new Person();
			 person.setFirstname(firstName);
			 person.setLastname(lastName);
			 person.setEmailid(emailId);
			 person.setAddress(address);
			 person.setCity(city);
			 person.setState(state);
			 person.setMembertype(memberType);
			 person.setZipcode(zipCode);
			 person.setCreditcardtype(creditCardType);
			 person.setCreditcardnum(creditCardNum);
			 person.setCreditcardcvv(Integer.parseInt(creditCardCVV));
			 
			 
		
			 
			 VLMSServiceProxy proxy = new VLMSServiceProxy();
			 String result="";
			 if(memberType.equals("SC")) {
				 System.out.println("Calling simple");
				 proxy.createSimpleCustomer(account, person);
			 }
			 else {
				 System.out.println("Calling Premium");
				 proxy.createPremiumCustomer(account, person);
			 }
			 
		 
			 Person tempPerson=proxy.retrievePersonByEmail(emailId);
			 personid=tempPerson.getPersonid();
			 person.setPersonid(personid);
			 session.setAttribute("Person",person);
			 session.setAttribute("Account", account);
			 
			 session.setAttribute("authenticated", "true");
			 session.setAttribute("MemberType", memberType);
			 
			 
			 if(memberType.equals("SC")) {
			 
				 SimpleCustomer simpleCustomer=proxy.retrieveSimpleCustomerByPersonId(String.valueOf(personid));
				 session.setAttribute("SimpleCustomer", simpleCustomer);
			 }
			 else {
			 
				 PremiumCustomer premiumCustomer=proxy.retrievePremiumCustomerByPersonId(String.valueOf(personid));
				 session.setAttribute("PremiumCustomer", premiumCustomer);
			 }
			 
			 destination = "/Home";
			 //response.sendRedirect(request.getContextPath + "");
			 request.setAttribute("message", "Welcome to Video Library");		
		}
		catch(RemoteException re) {	 
			 request.setAttribute("message", re.getMessage());
			 re.printStackTrace();
			 destination = "/signUp.jsp";
		 }
		 catch(Exception e) {
			 request.setAttribute("message", e.getMessage());
			 e.printStackTrace();
			 destination = "/signUp.jsp";
		 }
		 
		 RequestDispatcher rd = this.getServletContext().getRequestDispatcher(destination);
		 rd.forward(request, response);
	}
	
	

	private boolean isValidZipCode(String zipCode) {
		// TODO Auto-generated method stub
		 
		 Pattern p = Pattern.compile("(([0-9]{5})|([0-9]{5}-[0-9]{4}))");

	      //Match the given string with the pattern
	    Matcher m = p.matcher(zipCode);

	      //check whether match is found 
	      return m.matches();
		
	}

	private boolean isValidEmailAddress(String aEmailAddress){
		
	      //Set the email pattern string
	      Pattern p = Pattern.compile("[a-zA-Z]*[0-9]*@[a-zA-Z]*.[a-zA-Z]*");

	      //Match the given string with the pattern
	      Matcher m = p.matcher(aEmailAddress);

	      //check whether match is found 
	      return m.matches();	      
	   
	}


}
